You can declare an identifier not only at the beginning of a block, but
anywhere within a compound statement. For instance:
int example(void)
{
int a = 2,b = 3,c = 4,d;
d = a+b;
int e = d+a; // e is now declared as an int.
e += 34;
return e;
}
The scope of the identifier extends to the end of the current block. Note that this is NOT an extension of the C language, since the new ANSI C standard accepts this as normal usage.
Within a for statement, you can declare local for loop variables. The
scope of these variables is finished when the for statement ends.
#include <stdio.h>
int main(void)
{
for (int i = 0; i< 2;i++) {
printf("outer i is %d\n",i);
for (int i = 0;i<2;i++) {
printf("i=%d\n",i);
}
}
return 0;
}
The output of this program is:
outer i is 0
i=0
i=1
outer i is 1
i=0
i=1
Note that the scope of the identifiers declared within a ‘for’ scope ends just when the for statement ends, and that the ‘for’ statement scope is a new scope. Modify the above example as follows to demonstrate this:
#include <stdio.h>
int main(void)
{
for (int i = 0; i< 2;i++) { 1
printf("outer i is %d\n",i); 2
int i = 87;
3
for (int i = 0;i<2;i++) { 4
printf("i=%d\n",i); 5
} 6
} 7
return 0; 8
}
At the innermost loop, there are three identifiers called ‘i’.
· The first i is the outer i. Its scope goes from line 1 to 7 — the scope of the for statement.
· The second i (87) is a local identifier of the compound statement that begins in line 1 and ends in line 7. Compound statements can always declare local variables.
· The third i is declared at the innermost for statement. Its scope starts in line 4 and goes up to line 6. It belongs to the scope created by the second for statement.
· Note that for each new scope, the identifiers of the same name are shadowed by the new ones, as you would normally expect in C.
This feature allows you to define some or all of the arguments of a function to have default values. If the arguments aren’t supplied, the compiler generates the default values and pass them to the called function.
Example :
int foo(int a,int b = 45,double c =
0.777) ;
The function « foo » needs always the first argument in a call, but if arguments b or c aren’t supllied they will default to 45 and 0.777 respectively.
There are then three types of call in this example :
foo(1) ;
// This is equivalentd to foo(1,45,0.777) ;
foo(1,2) ;
// This is equivalent to foo(1,2,0.777) ;
foo(1,3,0.1) ;